package org.example.Day4.paixu;

import java.util.Arrays;

public class Test {
    public static void main(String[] args){
        int[] arr ={7, 23, 79, 81, 103, 127, 131, 147};
        for(int i=0;i<arr.length-1;i++){
            for(int j=i+1;j<arr.length;j++){
                if(arr[i]>arr[j]){
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[i] =temp;
                }
            }
        }
        binarySearch(arr,81);
        System.out.println("选择排序后"+Arrays.toString(arr));
        System.out.println(Arrays.binarySearch(arr,81));

    }
    public static int binarySearch(int[] arr,int data){
        int left=0;
        int right = arr.length-1;
        //定义循环控制折半
        while(left<=right){
            //折半之后找出中间索引
            int middle = (left+right)/2;
            //判断当前元素值与中间元素值大小情况
            if(data <arr[middle]){
                //往左边找截止位置（右边）=中间位置-1
                right = middle-1;
            }else if(data>arr[middle]){
                //往右边找 起始位置（左边） = 中间-1
                left = middle +1;
            }else{
                //中间位置正好是找的数
                return middle;
            }
        }
        return -1;
    }

}
